<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="业务日期" prop="businessDate">
        <el-date-picker clearable v-model="queryParams.businessDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择业务日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="单据编号" prop="receiptCode">
        <el-input v-model="queryParams.receiptCode" placeholder="请输入单据编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户ID" prop="customerId">
        <el-input v-model="queryParams.customerId" placeholder="请输入客户ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="应收金额" prop="totalAmount">
        <el-input v-model="queryParams.totalAmount" placeholder="请输入应收金额" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="抹零金额" prop="roundingAmount">
        <el-input v-model="queryParams.roundingAmount" placeholder="请输入抹零金额" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="实收金额" prop="actualPayment">
        <el-input v-model="queryParams.actualPayment" placeholder="请输入实收金额" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="待收金额" prop="pendingPayment">
        <el-input v-model="queryParams.pendingPayment" placeholder="请输入待收金额" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="业务员ID" prop="salespersonId">
        <el-input v-model="queryParams.salespersonId" placeholder="请输入业务员ID" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="操作" prop="operation">
        <el-input v-model="queryParams.operation" placeholder="请输入操作" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:sales:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:receipt:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:receipt:remove']">删除</el-button>
        </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:sales:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="自增长主键" align="center" prop="id" />
      <el-table-column label="业务日期" align="center" prop="businessDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.businessDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据编号" align="center" prop="receiptCode" />
      <el-table-column label="客户ID" align="center" prop="customerId" />
      <el-table-column label="应收金额" align="center" prop="totalAmount" />
      <el-table-column label="抹零金额" align="center" prop="roundingAmount" />
      <el-table-column label="实收金额" align="center" prop="actualPayment" />
      <el-table-column label="待收金额" align="center" prop="pendingPayment" />
      <el-table-column label="收款状态" align="center" prop="paymentStatus" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="业务员ID" align="center" prop="salespersonId" />
      <!-- <el-table-column label="单据状态" align="center" prop="status" /> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['business:receipt:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:receipt:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:receipt:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改进货单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body class="receipt-dialog"
      :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="receipt-container">
          <!-- 顶部信息区域 -->
          <div class="receipt-header">
            <div class="header-left">
              <div class="info-item">
                <span class="label">客户</span>
                <div class="customer-select-wrapper">
                  <el-popover placement="bottom-start" trigger="manual" v-model="customerPopoverVisible"
                    popper-class="customer-table-popover">
                    <div class="customer-table-wrapper" @mouseenter="isMouseInCustomerPopover = true"
                      @mouseleave="isMouseInCustomerPopover = false">
                      <el-table :data="customerList" border height="250" highlight-current-row
                        @row-click="handleCustomerSelect" v-loading="customerLoading">
                        <el-table-column prop="customerName" label="客户名称" width="150"></el-table-column>
                        <el-table-column prop="contactPerson" label="联系人" width="100"></el-table-column>
                        <el-table-column prop="contactPhone" label="联系电话" width="120"></el-table-column>
                        <el-table-column prop="priceLevel" label="价格等级" width="80"></el-table-column>
                        <el-table-column prop="exclusiveDiscount" label="专属折扣" width="80"></el-table-column>
                      </el-table>
                      <!-- 添加分页组件 -->
                      <el-pagination @size-change="handleCustomerSizeChange"
                        @current-change="handleCustomerCurrentChange" :current-page="customerPageNum"
                        :page-sizes="[10, 20, 30, 50]" :page-size="customerPageSize"
                        layout="total, sizes, prev, pager, next, jumper" :total="customerTotal" background
                        class="customer-pagination">
                      </el-pagination>
                    </div>
                    <el-input size="small" style="width: 150px;" slot="reference" v-model="customerKeyword"
                      placeholder="请选择客户" @focus="showCustomerPopover" @input="searchCustomers"
                      @blur="handleCustomerInputBlur" class="supplier-input">
                    </el-input>
                  </el-popover>
                  <!-- <div v-if="form.customerId" class="selected-customer-info">
                    已选择: {{ selectedCustomerName }}
                  </div> -->
                </div>
              </div>
            </div>
            <div class="header-right">
              <div class="info-item">
                <span class="label">业务员</span>
                <el-select v-model="form.salesman" placeholder="请选择业务员" size="small" class="salesman-select">
                  <el-option :label="userName" :value="userName"></el-option>
                </el-select>
              </div>
              <div class="info-item">
                <span class="label">单据日期</span>
                <el-date-picker v-model="form.businessDate" type="date" placeholder="选择日期" size="small"
                  value-format="yyyy-MM-dd" class="date-picker">
                </el-date-picker>
              </div>
            </div>
          </div>

          <!-- 商品导入按钮 -->
          <div class="goods-import">
            <el-button size="small" type="primary" plain @click="handleImportGoods">导入商品</el-button>
          </div>

          <!-- 商品表格 -->
          <div class="goods-table">
            <el-table :data="form.goodsList" border size="small"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266' }" :cell-style="{ padding: '5px 0' }"
              :row-class-name="tableRowClassName" @cell-mouse-enter="handleRowHover" @cell-mouse-leave="handleRowLeave"
              highlight-current-row style="width: 100%" max-height="480">
              <el-table-column type="index" label="" width="50" align="center">
                <template slot-scope="scope">
                  <div class="index-cell">
                    <span v-show="hoveredRow !== scope.$index">{{ scope.$index + 1 }}</span>
                    <div v-show="hoveredRow === scope.$index" class="index-operations">
                      <i class="el-icon-plus" @click.stop="handleAddRow(scope.$index)"></i>
                      <i class="el-icon-minus" @click.stop="handleDeleteRow(scope.$index)"></i>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="商品名称" min-width="180" align="center">
                <template slot-scope="scope">
                  <div class="goods-name-cell" @mouseenter="handleGoodsNameHover(scope.$index, true)"
                    @mouseleave="handleGoodsNameHover(scope.$index, false)"
                    :class="{ 'cell-hovered': !scope.row.goodsId && (hoveredRowIndex === scope.$index || focusedRowIndex === scope.$index) }">
                    <el-input v-model="scope.row.goodsSpec" size="small"
                      :placeholder="!scope.row.goodsId && (hoveredRowIndex === scope.$index || focusedRowIndex === scope.$index) ? '输入商品名称/规格/货号/条形码' : ''"
                      class="no-border goods-name-input" :disabled="!!scope.row.goodsId"
                      @focus="handleGoodsNameFocus(scope.$index)" @blur="handleGoodsNameBlur"
                      @input="handleGoodsSearch(scope.row.goodsSpec, scope.$index, 'goodsSpec')">
                    </el-input>
                    <div
                      v-show="hoveredRowIndex === scope.$index || focusedRowIndex === scope.$index || !!scope.row.goodsId"
                      class="select-btn-wrapper">
                      <el-button size="mini" type="text" class="select-btn" @click="openGoodsSelect(scope.$index)">
                        选择
                      </el-button>
                    </div>
                  </div>
                  <!-- 搜索结果下拉框 - 使用 el-table -->
                  <div
                    v-if="searchVisible && activeSearchRow === scope.$index && activeSearchField === 'goodsSpec' && !scope.row.goodsId"
                    class="search-dropdown">
                    <el-table :data="searchResults" size="small" highlight-current-row
                      @row-click="row => selectSearchGoods(row, scope.$index)" style="width: 100%">
                      <el-table-column prop="goodsSpec" label="商品名称" min-width="120"></el-table-column>
                      <el-table-column prop="specification" label="规格" width="100"></el-table-column>
                      <el-table-column prop="goodsCode" label="编号/货号" width="100"></el-table-column>
                      <el-table-column prop="stockQuantity" label="库存" width="80"></el-table-column>
                    </el-table>
                    <div v-if="searchResults.length === 0" class="search-empty">无匹配商品</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="规格" width="120" align="center">
                <template slot-scope="scope">
                  <div class="input-cell" @mouseenter="handleCellHover(scope.$index, 'specification', true)"
                    @mouseleave="handleCellHover(scope.$index, 'specification', false)"
                    :class="{ 'cell-hovered': hoveredCell.index === scope.$index && hoveredCell.field === 'specification' || focusedCell.index === scope.$index && focusedCell.field === 'specification' }">
                    <el-input v-model="scope.row.specification" size="small" :disabled="!scope.row.goodsId"
                      class="no-border" @focus="handleCellFocus(scope.$index, 'specification')" @blur="handleCellBlur">
                    </el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="编号/货号" width="120" align="center">
                <template slot-scope="scope">
                  <div class="input-cell"
                    @mouseenter="!scope.row.goodsId && handleCellHover(scope.$index, 'code', true)"
                    @mouseleave="!scope.row.goodsId && handleCellHover(scope.$index, 'code', false)"
                    :class="{ 'cell-hovered': !scope.row.goodsId && (hoveredCell.index === scope.$index && hoveredCell.field === 'code' || focusedCell.index === scope.$index && focusedCell.field === 'code') }">
                    <el-input v-model="scope.row.code" size="small" class="no-border" :disabled="!!scope.row.goodsId"
                      @focus="handleCellFocus(scope.$index, 'code')" @blur="handleCellBlur"
                      @input="handleGoodsSearch(scope.row.code, scope.$index, 'code')">
                    </el-input>
                  </div>
                  <!-- 搜索结果下拉框 -->
                  <div
                    v-if="searchVisible && activeSearchRow === scope.$index && activeSearchField === 'code' && !scope.row.goodsId"
                    class="search-dropdown">
                    <el-table :data="searchResults" size="small" highlight-current-row
                      @row-click="row => selectSearchGoods(row, scope.$index)" style="width: 100%">
                      <el-table-column prop="goodsSpec" label="商品名称" min-width="120"></el-table-column>
                      <el-table-column prop="specification" label="规格" width="100"></el-table-column>
                      <el-table-column prop="goodsCode" label="编号/货号" width="100"></el-table-column>
                      <el-table-column prop="stockQuantity" label="库存" width="80"></el-table-column>
                    </el-table>
                    <div v-if="searchResults.length === 0" class="search-empty">无匹配商品</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="条形码" width="120" align="center">
                <template slot-scope="scope">
                  <div class="input-cell"
                    @mouseenter="!scope.row.goodsId && handleCellHover(scope.$index, 'barcode', true)"
                    @mouseleave="!scope.row.goodsId && handleCellHover(scope.$index, 'barcode', false)"
                    :class="{ 'cell-hovered': !scope.row.goodsId && (hoveredCell.index === scope.$index && hoveredCell.field === 'barcode' || focusedCell.index === scope.$index && focusedCell.field === 'barcode') }">
                    <el-input v-model="scope.row.barcode" size="small" class="no-border" :disabled="!!scope.row.goodsId"
                      @focus="handleCellFocus(scope.$index, 'barcode')" @blur="handleCellBlur"
                      @input="handleGoodsSearch(scope.row.barcode, scope.$index, 'barcode')">
                    </el-input>
                  </div>
                  <!-- 搜索结果下拉框 -->
                  <div
                    v-if="searchVisible && activeSearchRow === scope.$index && activeSearchField === 'barcode' && !scope.row.goodsId"
                    class="search-dropdown">
                    <el-table :data="searchResults" size="small" highlight-current-row
                      @row-click="row => selectSearchGoods(row, scope.$index)" style="width: 100%">
                      <el-table-column prop="goodsSpec" label="商品名称" min-width="120"></el-table-column>
                      <el-table-column prop="specification" label="规格" width="100"></el-table-column>
                      <el-table-column prop="goodsCode" label="编号/货号" width="100"></el-table-column>
                      <el-table-column prop="stockQuantity" label="库存" width="80"></el-table-column>
                    </el-table>
                    <div v-if="searchResults.length === 0" class="search-empty">无匹配商品</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="单位" width="80" align="center">
                <template slot-scope="scope">
                  <div class="input-cell" @mouseenter="handleCellHover(scope.$index, 'unit', true)"
                    @mouseleave="handleCellHover(scope.$index, 'unit', false)"
                    :class="{ 'cell-hovered': hoveredCell.index === scope.$index && hoveredCell.field === 'unit' || focusedCell.index === scope.$index && focusedCell.field === 'unit' }">
                    <el-input v-model="scope.row.unit" size="small" :disabled="!scope.row.goodsId" class="no-border"
                      @focus="handleCellFocus(scope.$index, 'unit')" @blur="handleCellBlur">
                    </el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="数量" width="100" align="center">
                <template slot-scope="scope">
                  <div class="input-cell" @mouseenter="handleCellHover(scope.$index, 'quantity', true)"
                    @mouseleave="handleCellHover(scope.$index, 'quantity', false)"
                    :class="{ 'cell-hovered': hoveredCell.index === scope.$index && hoveredCell.field === 'quantity' || focusedCell.index === scope.$index && focusedCell.field === 'quantity' }">
                    <el-input v-model="scope.row.quantity" size="small" :disabled="!scope.row.goodsId"
                      controls-position="right" @change="calculateRowAmount(scope.row)" class="no-border number-input"
                      @focus="handleCellFocus(scope.$index, 'quantity')" @blur="handleCellBlur">
                    </el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="单价" width="100" align="center">
                <template slot-scope="scope">
                  <div class="input-cell" @mouseenter="handleCellHover(scope.$index, 'unitPrice', true)"
                    @mouseleave="handleCellHover(scope.$index, 'unitPrice', false)"
                    :class="{ 'cell-hovered': hoveredCell.index === scope.$index && hoveredCell.field === 'unitPrice' || focusedCell.index === scope.$index && focusedCell.field === 'unitPrice' }">
                    <el-input v-model="scope.row.unitPrice" size="small" :disabled="!scope.row.goodsId"
                      controls-position="right" @change="calculateRowAmount(scope.row)" class="no-border number-input"
                      @focus="handleCellFocus(scope.$index, 'unitPrice')" @blur="handleCellBlur">
                    </el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="金额" width="100" align="center">
                <template slot-scope="scope">
                  <div class="input-cell" @mouseenter="handleCellHover(scope.$index, 'totalPrice', true)"
                    @mouseleave="handleCellHover(scope.$index, 'totalPrice', false)"
                    :class="{ 'cell-hovered': hoveredCell.index === scope.$index && hoveredCell.field === 'totalPrice' || focusedCell.index === scope.$index && focusedCell.field === 'totalPrice' }">
                    <el-input v-model="scope.row.totalPrice" size="small" :disabled="!scope.row.goodsId"
                      controls-position="right" @change="calculateRowFromAmount(scope.row)"
                      class="no-border number-input" @focus="handleCellFocus(scope.$index, 'totalPrice')"
                      @blur="handleCellBlur">
                    </el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="备注" min-width="120" align="center">
                <template slot-scope="scope">
                  <div class="input-cell" @mouseenter="handleCellHover(scope.$index, 'remark', true)"
                    @mouseleave="handleCellHover(scope.$index, 'remark', false)"
                    :class="{ 'cell-hovered': hoveredCell.index === scope.$index && hoveredCell.field === 'remark' || focusedCell.index === scope.$index && focusedCell.field === 'remark' }">
                    <el-input v-model="scope.row.remark" size="small" placeholder="" class="no-border"
                      @focus="handleCellFocus(scope.$index, 'remark')" @blur="handleCellBlur">
                    </el-input>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 表格底部汇总 -->
            <div class="table-footer">
              <div class="footer-summary">
                <span>数量 {{form.goodsList && form.goodsList.length > 0 ? form.goodsList.reduce((sum, item) => sum +
                  (parseFloat(item.quantity) || 0), 0).toFixed(2) : '0.00'}}</span>
                <span class="amount-text">金额 ¥{{form.goodsList && form.goodsList.length > 0 ?
                  form.goodsList.reduce((sum,
                    item) => sum + (parseFloat(item.totalPrice) || 0), 0).toFixed(2) : '0.00'}}</span>
              </div>
            </div>
          </div>

          <!-- 底部结算区域 - 完全按照UI图还原 -->
          <div class="bottom-section">
            <!-- 折扣和金额计算区域 -->
            <div class="calculation-area">
              <!-- 折扣/优惠金额输入行 -->
              <div class="calc-row">
                <div class="calc-label">
                  <el-dropdown trigger="click" @command="switchDiscountType" placement="bottom-start">
                    <span class="dropdown-label">
                      {{ form.discountType === 'percent' ? '折扣' : '优惠金额' }}
                      <i class="el-icon-arrow-down"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="percent">折扣</el-dropdown-item>
                      <el-dropdown-item command="amount">优惠金额</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
                <div class="calc-input">
                  <div class="input-with-unit">
                    <el-input v-if="form.discountType === 'percent'" v-model="form.discount" size="small"
                      :disabled="!form.goodsList || !this.form.goodsList.some(item => item.goodsId)"
                      @input="calculateTotal" placeholder="100">
                    </el-input>
                    <span v-if="form.discountType === 'percent'" class="input-unit">%</span>

                    <el-input v-else v-model="form.discount" size="small"
                      :disabled="!form.goodsList || !this.form.goodsList.some(item => item.goodsId)"
                      @input="calculateTotal" placeholder="0.00">
                    </el-input>
                  </div>
                </div>
                <div class="calc-label">折后金额</div>
                <div class="calc-input">
                  <el-input v-model="form.discountedAmount" size="small" disabled></el-input>
                </div>
                <div class="calc-label">运费</div>
                <div class="calc-input">
                  <el-input v-model="form.freight" size="small" @input="handleFreightChange" placeholder="0.00">
                  </el-input>
                </div>
              </div>

              <div class="calc-row total-row">
                <div class="calc-label">本单应付</div>
                <div class="total-value">{{ form.totalAmount }}</div>
              </div>

              <div class="calc-row">
                <div class="calc-label">本次实付</div>
                <div class="calc-input">
                  <el-tooltip content="请先选择客户" placement="top" :disabled="!!form.customerId">
                    <el-input v-model="form.actualPayment" size="small" @input="handleActualPaymentChange"
                      placeholder="0.00" :disabled="!form.customerId">
                    </el-input>
                  </el-tooltip>
                </div>
                <div class="payment-method">
                  <el-select v-model="form.paymentMethod" placeholder="现金" size="small">
                    <el-option label="现金" value="现金"></el-option>
                    <el-option label="微信" value="微信"></el-option>
                    <el-option label="支付宝" value="支付宝"></el-option>
                    <el-option label="银行卡" value="银行卡"></el-option>
                    <el-option label="转账" value="转账"></el-option>
                  </el-select>
                </div>
              </div>
            </div>

            <!-- 备注区域 -->
            <div class="remark-section">
              <div class="remark-label">备注</div>
              <el-input type="textarea" v-model="form.remark" :rows="3" placeholder="请输入单据备注(ctrl/shift+回车可换行)"
                class="remark-textarea">
              </el-input>
              <el-upload action="#" :auto-upload="false" :on-change="handleFileChange" :file-list="form.fileList"
                class="attachment-upload">
                <div class="upload-button">
                  <i class="el-icon-plus"></i>
                  <div class="upload-text">上传附件</div>
                </div>
              </el-upload>
              <div class="upload-tips">
                <p>最多上传5个附件，每个附件最大10MB</p>
                <p>支持"拖拽上传"和"复制粘贴上传"</p>
              </div>
            </div>
          </div>
        </div>
      </el-form>

      <!-- 添加对话框底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 货品导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx" action="#" :auto-upload="false" :show-file-list="true"
        :before-upload="handleBeforeUpload" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            单次最多导入600条商品，超过600条可分多次导入
          </div>
          <span>仅允许导入xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品选择弹窗 -->
    <goods-selector v-model="goodsSelectorVisible" :active-row-index="activeRowIndex" @confirm="handleGoodsConfirm"
      @cancel="handleGoodsCancel">
    </goods-selector>

    <!-- 商品选择器组件 -->
    <goods-selector v-model="goodsSelectVisible" :active-row-index="activeRowIndex" :receipt-code="form.receiptCode"
      @confirm="handleGoodsSelectConfirm" @cancel="goodsSelectVisible = false">
    </goods-selector>

    <!-- 查看进货单对话框 -->
    <el-dialog :title="'查看进货单：' + viewForm.receiptCode" :visible.sync="viewOpen" width="1200px" append-to-body
      class="receipt-dialog">
      <div class="receipt-view-container">
        <!-- 顶部信息区域 -->
        <div class="receipt-header">
          <div class="header-left">
            <div class="info-item">
              <span>客户：</span>
              <span>{{ viewForm.customerName }}</span>
            </div>
          </div>
          <!-- <div class="info-item">
            <span >业务员：</span>
            <span>{{ viewForm.salesman }}</span>
          </div> -->
          <div class="info-item">
            <span>单据日期：</span>
            <span>{{ viewForm.businessDate }}</span>
          </div>
          <div class="info-item">
            <span>制单时间：</span>
            <span>{{ viewForm.createTime }}</span>
          </div>
          <div class="info-item">
            <span>制单人：</span>
            <span>{{ userName }}</span>
          </div>
        </div>

        <!-- 商品表格 -->
        <div class="goods-table">
          <el-table :data="viewForm.goodsList" border size="small"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }" :cell-style="{ padding: '5px 0' }"
            style="width: 100%" max-height="480">
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column label="商品名称" min-width="180" align="center" prop="goodsSpec"></el-table-column>
            <el-table-column label="规格" width="120" align="center" prop="specification"></el-table-column>
            <el-table-column label="编号/货号" width="120" align="center" prop="goodsCode"></el-table-column>
            <!-- <el-table-column label="条形码" width="120" align="center" prop="barcode"></el-table-column> -->
            <el-table-column label="单位" width="80" align="center" prop="unit"></el-table-column>
            <el-table-column label="数量" width="80" align="center" prop="quantity"></el-table-column>
            <el-table-column label="单价" width="100" align="center" prop="unitPrice"></el-table-column>
            <el-table-column label="金额" width="100" align="center" prop="totalPrice"></el-table-column>
            <el-table-column label="备注" min-width="120" align="center" prop="remark"></el-table-column>
          </el-table>

          <!-- 表格底部汇总 -->
          <div class="table-footer">
            <div class="footer-summary">
              <span>数量 {{viewForm.goodsList && viewForm.goodsList.length > 0 ? viewForm.goodsList.reduce((sum, item) =>
                sum
                + (parseFloat(item.quantity) || 0), 0).toFixed(0) : '0'}}</span>
              <span class="amount-text">金额 ¥{{viewForm.goodsList && viewForm.goodsList.length > 0 ?
                viewForm.goodsList.reduce((sum, item) => sum + (parseFloat(item.totalPrice) || 0), 0).toFixed(2) :
                '0.00'
                }}</span>
            </div>
          </div>
        </div>

        <!-- 底部结算区域 -->
        <div class="bottom-watch-section">
          <div class="bottom-area">
            <div class="calc-row">
              <div class="calc-label-buttom">{{ viewForm.discountType === 'percent' || !viewForm.discountType ? '折扣' :
                '优惠金额'
                }}:</div>
              <div class="calc-input">
                <span>{{ viewForm.discountType === 'percent' || !viewForm.discountType ? `${viewForm.discount || 100}%` :
                  `${viewForm.discount || 0}` }}</span>
              </div>
              <!-- <div class="calc-input" style="margin-left: 15px;">
                <span v-if="viewForm.discountType === 'percent'">{{ viewForm.discount }}%</span>
                <span v-else>{{ viewForm.discountAmount }}</span>
              </div> -->
              <div class="calc-label-buttom">折后金额:</div>
              <div class="calc-input">
                <span>{{ viewForm.discountedAmount }}</span>
              </div>
              <div style="width: 40px;">运费:</div>
              <div class="calc-input">
                <span>{{ viewForm.freight ||0}}</span>
              </div>
            </div>

            <div class="calc-row">
              <!-- <div class="calc-label">订金抵扣</div>
              <div class="calc-input">
                <span>{{ viewForm.depositDeduction }}</span>
              </div> -->
              <div class="calc-label-buttom">应付金额:</div>
              <div class="calc-input">
                <span style="color: #54B6CB; font-weight: bold;">{{ viewForm.totalAmount }}</span>
              </div>
              <!-- <div class="calc-label">本次实付</div>
              <div class="calc-input">
                <span>{{ viewForm.actualPayment }}</span>
              </div>
              <div class="calc-label">待付金额</div>
              <div class="calc-input">
                <span>{{ viewForm.pendingPayment }}</span>
              </div> -->
            </div>

            <div class="calc-row">
              <div class="calc-label-buttom">本单已付:</div>
              <div class="calc-input">
                <span style="margin-right: 20px;">{{ viewForm.actualPayment }}</span>
                <span style="color: #8B9699;">{{ viewForm.paymentMethod }}</span>
              </div>
            </div>
          </div>

          <!-- 备注区域 -->
          <div class="remark-section">
            <span class="remark-label">备注:</span>
            <span class="remark-content">{{ viewForm.remark }}</span>
          </div>

          <!-- 附件区域 -->
          <div class="attachment-section" v-if="viewForm.paymentAttachment">
            <div class="attachment-label">支付附件</div>
            <div class="attachment-content">
              <el-image v-if="viewForm.paymentAttachment" :src="getImageUrl(viewForm.paymentAttachment)"
                style="max-width: 200px; max-height: 200px;"
                :preview-src-list="[getImageUrl(viewForm.paymentAttachment)]">
              </el-image>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSales, getSales, delSales, addSales, updateSales, getSalesByReceiptCode } from "@/api/business/sales";
import { listCustomer, getCustomer } from "@/api/business/customer";
import { getCategory } from "@/api/business/supplierCategory";
import { listGoods } from "@/api/business/goods";
import { listCategory } from "@/api/business/supplierCategory";
import { getToken } from "@/utils/auth";
import GoodsSelector from "@/components/GoodsSelector";
import * as XLSX from 'xlsx';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { mapState } from 'vuex'

export default {
  name: "Sales",
  components: {
    GoodsSelector,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 进货单表格数据
      receiptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiptCode: null,
        supplierId: null,
        businessDate: null,
        totalAmount: null,
        depositDeduction: null,
        actualPayment: null,
        pendingPayment: null,
        paymentMethod: null,
        paymentAttachment: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 查看进货单对话框是否显示
      viewOpen: false,
      // 查看进货单表单数据
      viewForm: {
        id: null,
        receiptCode: "",
        supplierName: "",
        supplierId: null,
        salesman: "",
        businessDate: "",
        totalAmount: "0.00",
        discountType: "percent",
        discount: "100",
        discountAmount: "0.00",
        discountedAmount: "0.00",
        freight: "0.00",
        depositDeduction: "0.00",
        actualPayment: "0.00",
        pendingPayment: "0.00",
        paymentMethod: "现金",
        paymentAttachment: null,
        status: "0",
        remark: "",
        goodsList: []
      },
      goodsSelectorVisible: false,
      goodsSearchKeyword: '',
      goodsSelectList: [],
      selectedGoods: [],
      showDiscountOptions: false,
      activeRowIndex: -1,
      hoveredRowIndex: -1,
      focusedRowIndex: -1,
      hoveredCell: {
        index: -1,
        field: ''
      },
      focusedCell: {
        index: -1,
        field: ''
      },
      hoveredRow: -1,
      searchResults: [],
      searchVisible: false,
      activeSearchRow: -1,
      activeSearchField: '',
      searchTimer: null,
      // 货品导入参数
      upload: {
        // 是否显示弹出层（货品导入）
        open: false,
        // 弹出层标题（货品导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的货品数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/goods/importData",
        // 图片上传地址
        imageUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      },
      supplierOptions: [],
      goodsSelectVisible: false,  // 商品选择器是否可见
      selectedGoodsList: [], // 添加已选商品列表

      // 客户选择相关
      selectedCustomer: null,
      customerPopoverVisible: false,
      customerKeyword: '',
      customerList: [],
      selectedCustomerName: '',
      customerSearchTimer: null,
      customerLoading: false,
      customerPageNum: 1,
      customerPageSize: 10,
      customerTotal: 0,

      // 添加一个标志变量，用于跟踪鼠标是否在弹窗内部
      isMouseInCustomerPopover: false,
    };
  },
  computed: {
    totalQuantity() {
      return this.form.goodsList.reduce((sum, item) => {
        return sum + (parseFloat(item.quantity) || 0);
      }, 0).toFixed(2);
    },
    totalAmount() {
      // 修改计算总金额的方法
      return this.form.goodsList.reduce((sum, item) => {
        return sum + (parseFloat(item.totalPrice) || 0);  // 使用 totalPrice 替代原来的计算
      }, 0);
    },
    hasSelectedGoods() {
      // 只需要判断 form.goodsList 即可
      return this.form.goodsList && this.form.goodsList.some(item => item.goodsId);
    },
    // 使用对象展开运算符将 state 中的用户信息映射到计算属性
    ...mapState({
      userId: state => state.user.id,
      userName: state => state.user.name,
      userAvatar: state => state.user.avatar,
      userRoles: state => state.user.roles,
      userPermissions: state => state.user.permissions
    })
  },
  created() {
    this.getList();
    this.getSupplierOptions();
    // 在组件创建时使用用户信息
    console.log('当前用户:', this.userName);
  },
  methods: {
    /** 查询销售单列表 */
    getList() {
      this.loading = true;
      listSales(this.queryParams).then(response => {
        this.receiptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置 - 修改reset方法
    reset() {
      this.form = {
        id: null,
        businessDate: new Date().toISOString().split('T')[0], // 设置为当天日期
        receiptCode: null,
        customerId: null,
        totalAmount: "0.00",
        roundingAmount: "0.00",
        discountType: "percent",
        discount: "100",
        discountAmount: "0.00",
        discountedAmount: "0.00",
        freight: "0.00",
        depositDeduction: "0.00",
        actualPayment: "0.00",
        pendingPayment: "0.00",
        paymentMethod: "现金",
        paymentAttachment: null,
        status: "0",
        remark: "",
        goodsList: [],  // 确保初始化为空数组
        fileList: []
      };

      // 重置客户选择相关的状态变量
      this.customerKeyword = '';
      this.selectedCustomerName = '';
      this.customerList = [];
      this.customerPageNum = 1;
      this.customerPopoverVisible = false;
      this.isMouseInCustomerPopover = false;

      // 重置搜索相关状态
      this.searchVisible = false;
      this.searchResults = [];
      this.activeSearchRow = -1;
      this.activeSearchField = '';

      // 重置表单验证
      this.resetForm("form");

      // 初始化空行
      this.initEmptyRows();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加销售单";
      // 设置业务员为当前登录用户
      this.form.salesman = this.userName;
      this.initEmptyRows(); // 初始化空行
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      this.reset();
      const id = row.id || this.ids
      getSales(id).then(response => {
        this.form = response.data;

        // 确保 goodsList 是数组
        this.form.goodsList = this.form.goodsList || [];

        // 修复折扣类型初始化
        if (row.discountType) {
          this.$set(this.form, 'discountType', row.discountType);
        } else if (this.form.discountAmount && parseFloat(this.form.discountAmount) > 0) {
          this.$set(this.form, 'discountType', 'amount');
          // 如果是金额折扣，将discountAmount值设置到discount字段
          this.$set(this.form, 'discount', this.form.discountAmount);
        } else {
          this.$set(this.form, 'discountType', 'percent');
          // 确保折扣百分比有效
          if (!this.form.discount || parseFloat(this.form.discount) <= 0) {
            this.$set(this.form, 'discount', '100');
          }
        }

        // 设置客户信息
        if (this.form.customerId) {
          // 获取客户信息并设置显示
          getCustomer(this.form.customerId).then(customerRes => {
            if (customerRes.code === 200 && customerRes.data) {
              this.selectedCustomerName = customerRes.data.customerName;
              this.customerKeyword = customerRes.data.customerName;
            }
          });
        }

        console.log('初始化后的表单:', JSON.parse(JSON.stringify(this.form)));

        // 保存原始的实付金额
        const originalActualPayment = this.form.actualPayment;

        // 如果没有业务员信息，则设置为当前用户
        if (!this.form.salesman) {
          this.form.salesman = this.userName;
        }

        // 获取商品列表
        if (this.form.receiptCode) {
          getSalesByReceiptCode(this.form.receiptCode).then(res => {
            if (res.code === 200 && res.data) {
              // 处理商品数据并直接设置到 form.goodsList
              this.form.goodsList = res.data.salesDetailItemList.map(item => ({
                id: item.id,
                goodsId: item.goodsId,
                goodsSpec: item.goodsSpec,
                specification: item.specification,
                goodsCode: item.goodsCode,
                barcode: item.barcode,
                unit: item.unit,
                quantity: item.quantity || 1,
                unitPrice: item.unitPrice || 0,
                totalPrice: item.totalPrice || ((item.quantity || 1) * (item.unitPrice || 0)).toFixed(2),
                remark: item.remark || ""
              }));

              // 计算总金额
              this.calculateTotal();

              // 恢复原始的实付金额
              this.$set(this.form, 'actualPayment', originalActualPayment);

              // 重新计算待付金额
              this.calculatePendingPayment();

              // 在商品列表加载完成后再打开对话框
              this.open = true;
              this.title = "修改销售单";
            }
          });
        } else {
          // 如果没有商品列表，直接打开对话框
          this.open = true;
          this.title = "修改销售单";
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 额外检查客户是否已选择
          if (!this.form.customerId) {
            this.$message.warning('请选择客户');
            return;
          }

          // 过滤掉没有商品ID的空行
          const validGoodsList = this.form.goodsList.filter(item => item.goodsId);

          if (validGoodsList.length === 0) {
            this.$message.warning('请至少添加一个商品');
            return;
          }

          // 构建提交的数据
          const submitData = {
            ...this.form,
            discount: Number(this.form.discount), // 确保discount是数字类型
            salesDetailItemList: validGoodsList
          };
          delete submitData.goodsList;
          console.log(submitData)
          if (this.form.id != null) {
            updateSales(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSales(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除进货单编号为"' + ids + '"的数据项？').then(function () {
        return delSales(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/receipt/export', {
        ...this.queryParams
      }, `receipt_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImportGoods() {
      this.upload.title = "货品导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('business/goods/importTemplate', {}, `goods_template_${new Date().getTime()}.xlsx`);
    },
    // 修改提交方法
    submitFileForm() {
      if (!this.$refs.upload.uploadFiles.length) {
        this.$message.warning("请先选择要导入的文件");
        return;
      }
      const file = this.$refs.upload.uploadFiles[0].raw;
      const reader = new FileReader();

      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const importedGoods = XLSX.utils.sheet_to_json(worksheet);

          if (importedGoods.length === 0) {
            this.$message.warning("导入的文件中没有商品数据");
            return;
          }

          // 找到最后一个有数据的行的索引
          let lastDataIndex = -1;
          for (let i = 0; i < this.form.goodsList.length; i++) {
            const row = this.form.goodsList[i];
            if (row.goodsId || row.goodsSpec || row.goodsCode) {
              lastDataIndex = i;
            }
          }

          // 获取插入位置（最后一个有数据的行之后）
          const insertIndex = lastDataIndex + 1;

          // 处理每个导入的商品
          importedGoods.forEach((good, index) => {
            const newGoodsRow = {
              id: null,
              goodsId: null,
              goodsSpec: good['品名规格(必填)'] || '',
              specification: good['规格'] || '',
              goodsCode: good['货品代码'] || '',
              barcode: good['条形码'] || '',
              unit: good['主计量单位'] || '',
              quantity: '1',
              price: (good['进货价'] || 0).toString(),
              amount: ((1) * (parseFloat(good['进货价']) || 0)).toFixed(2),
              remark: good['备注'] || '',
              supplyGoodsName: good['供应商品名'] || '',
              primaryUnit: good['主计量单位'] || '',
              secondaryUnit: good['辅助单位'] || '',
              conversionRate: good['换算率'] || '1',
              stockQuantity: good['库存数量'] || '0',
              initialCost: good['期初成本'] || '0',
              purchasePrice: good['进货价'] || '0',
              retailPrice: good['零售价'] || '0',
              wholesalePrice1: good['批发价1'] || '0',
              wholesalePrice2: good['批发价2'] || '0',
              maxStock: good['最高库存'] || '0',
              minStock: good['最低库存'] || '0',
              goodsCategoryId: good['货品类别'] || null
            };

            // 检查商品是否已存在
            const existingIndex = this.form.goodsList.findIndex(item =>
              item.goodsId && item.goodsCode === newGoodsRow.goodsCode
            );

            if (existingIndex >= 0) {
              // 如果商品已存在，更新数量
              const currentQuantity = parseFloat(this.form.goodsList[existingIndex].quantity) || 0;
              this.form.goodsList[existingIndex].quantity = (currentQuantity + 1).toString();
              this.calculateRowAmount(this.form.goodsList[existingIndex]);
            } else {
              // 在正确位置插入新商品
              if (insertIndex + index < this.form.goodsList.length) {
                // 如果位置在现有数组范围内，使用 Vue.set 更新
                this.$set(this.form.goodsList, insertIndex + index, newGoodsRow);
              } else {
                // 如果超出范围，追加到末尾
                this.form.goodsList.push(newGoodsRow);
              }
            }
          });

          // 强制更新视图
          this.$nextTick(() => {
            this.form.goodsList = [...this.form.goodsList];
            // 更新总金额
            this.calculateTotal();
          });

          this.$message.success(`成功导入 ${importedGoods.length} 个商品`);
          this.upload.open = false;
          this.$refs.upload.clearFiles();

        } catch (error) {
          console.error('处理导入数据时出错:', error);
          this.$message.error("处理导入数据时出错，请确保文件格式正确");
        }
      };

      reader.readAsArrayBuffer(file);
    },
    searchGoods() {
      // 调用商品API获取商品列表
      listGoods({
        goodsSpec: this.goodsSearchKeyword,
        pageNum: 1,
        pageSize: 10
      }).then(response => {
        this.goodsSelectList = response.rows || [];
      });
    },
    handleGoodsSelectionChange(selection) {
      this.selectedGoods = selection;
    },
    handleGoodsConfirm(selectedGoods) {
      console.log('选中的商品:', selectedGoods);
      if (selectedGoods.length > 0 && this.activeRowIndex >= 0) {
        // 获取当前行的商品信息
        const currentRow = this.form.goodsList[this.activeRowIndex];
        let goodsToProcess = [...selectedGoods];

        // 如果当前行有商品，检查是否在选中列表中
        if (currentRow && currentRow.goodsId) {
          const matchingGoodIndex = goodsToProcess.findIndex(g => g.id === currentRow.goodsId);

          if (matchingGoodIndex >= 0) {
            // 当前商品在选中列表中，先更新当前行
            this.updateGoodsRow(this.activeRowIndex, goodsToProcess[matchingGoodIndex]);
            // 从待处理列表中移除已使用的商品
            goodsToProcess.splice(matchingGoodIndex, 1);
          } else if (goodsToProcess.length > 0) {
            // 当前商品不在选中列表中，使用第一个选中的商品替换
            this.updateGoodsRow(this.activeRowIndex, goodsToProcess[0]);
            goodsToProcess.splice(0, 1);
          }
        } else if (goodsToProcess.length > 0) {
          // 如果当前行没有商品，使用第一个选中的商品
          this.updateGoodsRow(this.activeRowIndex, goodsToProcess[0]);
          goodsToProcess.splice(0, 1);
        }

        // 处理剩余的商品，插入并移动后续行
        if (goodsToProcess.length > 0) {
          let insertIndex = this.activeRowIndex + 1;

          // 计算需要移动的现有行
          const existingRows = this.form.goodsList.slice(insertIndex);
          // 移除这些行
          this.form.goodsList.splice(insertIndex);

          // 插入新的商品行
          goodsToProcess.forEach(good => {
            const newRow = this.createGoodsRow(good);
            this.form.goodsList.push(newRow);
          });

          // 将原有的行添加到末尾
          existingRows.forEach(row => {
            this.form.goodsList.push(row);
          });
        }

        // 强制更新视图
        this.form.goodsList = [...this.form.goodsList];

        // 重新计算总金额
        this.calculateTotal();
      }

      // 关闭选择器
      this.goodsSelectorVisible = false;

      // 清除焦点状态
      setTimeout(() => {
        this.focusedRowIndex = -1;
      }, 500);
    },
    handleGoodsCancel() {
      this.goodsSelectorVisible = false;
    },
    calculateRowAmount(row) {
      if (row.goodsId && row.quantity && row.unitPrice) {
        // 计算金额并保留两位小数
        row.totalPrice = (parseFloat(row.quantity) * parseFloat(row.unitPrice)).toFixed(2);
      }

      // 更新总计
      this.calculateTotal();
    },
    calculateTotal() {
      // 确保 goodsList 存在且是数组
      if (!this.form.goodsList) {
        this.form.goodsList = [];  // 如果不存在则初始化为空数组
        return;
      }

      // 计算商品总金额
      const totalAmount = this.form.goodsList.reduce((sum, item) => {
        return sum + (parseFloat(item.totalPrice) || 0);
      }, 0);

      // 根据折扣类型计算折后金额
      let discountedAmount;

      if (this.form.discountType === 'percent') {
        // 百分比折扣
        const discountPercent = parseFloat(this.form.discount) || 100;
        discountedAmount = (totalAmount * (discountPercent / 100)).toFixed(2);
      } else {
        // 金额折扣
        const discountAmount = parseFloat(this.form.discount) || 0;
        discountedAmount = (totalAmount - discountAmount).toFixed(2);
      }

      // 更新折后金额
      this.form.discountedAmount = discountedAmount;

      // 计算本单应付（折后金额 + 运费）
      const freight = parseFloat(this.form.freight) || 0;
      const finalAmount = (parseFloat(discountedAmount) + freight).toFixed(2);

      // 更新本单应付
      this.form.totalAmount = finalAmount;

      // 只在新增模式下设置本次实付等于本单应付
      if (!this.form.id) {
        this.form.actualPayment = finalAmount;
      }

      // 更新待付金额
      this.calculatePendingPayment();
    },
    calculateGoodsTotal() {
      return this.form.goodsList.reduce((sum, item) => {
        return sum + ((parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0));
      }, 0);
    },
    handleFreightChange() {
      this.calculateTotal();  // 直接调用计算方法，不需要额外检查
    },
    calculateTotalByDiscountAmount() {
      // 直接调用计算方法，确保折后金额更新
      this.calculateTotal();
    },
    calculatePendingPayment() {
      const totalAmount = parseFloat(this.form.totalAmount) || 0;
      const actualPayment = parseFloat(this.form.actualPayment) || 0;
      // 待付金额 = 本单应付 - 本次实付
      this.form.pendingPayment = (totalAmount - actualPayment).toFixed(2);
    },
    tableRowClassName({ row, rowIndex }) {
      return 'hoverable-row';
    },
    handleRowHover(row, column, cell, event) {
      this.hoveredRow = this.form.goodsList.indexOf(row);
    },
    handleRowLeave(row, column, cell, event) {
      this.hoveredRow = -1;
    },
    handleAddRow(index) {
      const newRow = {
        id: null,
        goodsId: null,
        goodsSpec: "",
        specification: "",
        goodsCode: "",
        barcode: "",
        unit: "",
        quantity: "",
        price: "",
        amount: "",
        remark: ""
      };
      this.form.goodsList.splice(index + 1, 0, newRow);
    },
    handleDeleteRow(index) {
      if (this.form.goodsList.length === 1) {
        this.$message.warning('至少保留一行商品');
        return;
      }
      this.form.goodsList.splice(index, 1);
    },
    handleGoodsNameHover(index, isHover) {
      this.hoveredRowIndex = isHover ? index : -1;
    },
    handleGoodsNameFocus(index) {
      this.focusedRowIndex = index;
    },
    handleGoodsNameBlur() {
      // 延迟隐藏搜索结果，以便能点击选项
      setTimeout(() => {
        this.searchVisible = false;
      }, 200);
    },
    openGoodsSelect(index) {
      console.log('打开商品选择器, 行索引:', index);
      this.activeRowIndex = index;

      // 重置选择器状态
      this.selectedGoodsList = [];

      // 如果当前行已有商品，将其添加到已选列表中
      if (this.form.goodsList[index] && this.form.goodsList[index].goodsId) {
        const currentGoods = this.form.goodsList[index];
        this.selectedGoodsList.push({
          id: currentGoods.goodsId,
          goodsSpec: currentGoods.goodsSpec,
          specification: currentGoods.specification,
          goodsCode: currentGoods.goodsCode,
          barcode: currentGoods.barcode,
          primaryUnit: currentGoods.unit,
          quantity: currentGoods.quantity,
          unitPrice: currentGoods.unitPrice,
          totalPrice: currentGoods.totalPrice,
          goodsImage: currentGoods.goodsImage
        });
      }

      // 打开选择器
      this.goodsSelectVisible = true;
    },
    handleCellHover(index, field, isHover) {
      if (isHover) {
        this.hoveredCell = { index, field };
      } else {
        this.hoveredCell = { index: -1, field: '' };
      }
    },
    handleCellFocus(index, field) {
      this.focusedCell = { index, field };
    },
    handleCellBlur() {
      // 延迟隐藏搜索结果，以便能点击选项
      setTimeout(() => {
        this.searchVisible = false;
      }, 200);
    },
    // 初始化空行
    initEmptyRows() {
      // 创建8个空行
      const emptyRows = Array(8).fill().map(() => ({
        id: null,
        goodsId: null,
        goodsSpec: "",
        specification: "",
        goodsCode: "",
        barcode: "",
        unit: "",
        quantity: "",
        price: "",
        amount: "",
        remark: ""
      }));

      this.form.goodsList = emptyRows;
    },
    handleGoodsSearch(value, index, field) {
      this.activeSearchRow = index;
      this.activeSearchField = field;

      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }

      // 设置新的定时器（防抖）
      this.searchTimer = setTimeout(() => {
        if (!value) {
          this.searchResults = [];
          this.searchVisible = false;
          return;
        }

        // 调用后端API搜索商品
        listGoods({
          [field]: value
        }).then(response => {
          this.searchResults = response.rows || [];
          this.searchVisible = true;
        });
      }, 300);
    },
    selectSearchGoods(item, index) {
      console.log('选择商品:', item, '行索引:', index);

      // 使用 $set 更新行数据的各个属性
      this.$set(this.form.goodsList, index, {
        id: null,
        goodsId: item.id,
        goodsSpec: item.goodsSpec || '',
        specification: item.specification || '',
        goodsCode: item.goodsCode || '',
        barcode: item.barcode || '',
        unit: item.primaryUnit || '',
        quantity: 1,
        price: item.purchasePrice || 0,
        amount: ((1) * (item.purchasePrice || 0)).toFixed(2),
        remark: ''
      });

      // 计算并设置金额
      this.calculateRowAmount(this.form.goodsList[index]);

      // 隐藏搜索结果
      this.searchVisible = false;

      // 清空搜索结果
      this.searchResults = [];
    },
    calculateRowFromAmount(row) {
      if (row.goodsId && row.totalPrice && row.quantity) {
        // 如果金额和数量都有值，计算单价
        row.unitPrice = (parseFloat(row.totalPrice) / parseFloat(row.quantity)).toFixed(2);
      } else if (row.goodsId && row.totalPrice && row.unitPrice) {
        // 如果金额和单价都有值，计算数量
        row.quantity = (parseFloat(row.totalPrice) / parseFloat(row.unitPrice)).toFixed(2);
      }

      // 更新总计
      this.calculateTotal();
    },
    // 更新商品行数据
    updateGoodsRow(index, goods) {
      console.log('更新商品行:', index, goods);

      // 如果索引超出范围，添加新行
      if (index >= this.form.goodsList.length) {
        this.form.goodsList.push({});
      }

      // 使用 $set 确保响应式更新
      this.$set(this.form.goodsList, index, {
        id: null,
        goodsId: goods.id,
        goodsSpec: goods.goodsSpec,
        specification: goods.specification,
        goodsCode: goods.goodsCode,
        barcode: goods.barcode,
        unit: goods.primaryUnit,
        quantity: goods.quantity || 1,
        unitPrice: goods.unitPrice || 0,
        totalPrice: goods.totalPrice || ((goods.quantity || 1) * (goods.unitPrice || 0)).toFixed(2),
        remark: ""
      });

      // 重新计算总金额
      this.calculateTotal();
    },
    // 创建新的商品行
    createGoodsRow(good) {
      return {
        id: null,
        goodsId: good.id,
        goodsSpec: good.goodsSpec,
        specification: good.specification,
        goodsCode: good.goodsCode,
        barcode: good.barcode,
        unit: good.primaryUnit,
        quantity: good.quantity || 1,
        price: good.price || good.purchasePrice || 0,
        amount: ((good.quantity || 1) * (good.price || good.purchasePrice || 0)).toFixed(2),
        remark: ""
      };
    },
    // 添加 before-upload 处理方法
    handleBeforeUpload(file) {
      const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isXLSX) {
        this.$message.error('只能上传 xlsx 格式的文件!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('文件大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    /** 获取供应商选项 */
    getSupplierOptions() {
      listCustomer().then(response => {
        // 直接使用返回的数据构建树形结构
        console.log(response)
        // this.supplierOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    /** 处理客户选择变化 */
    handleCustomerChange(value) {
      if (!value) {
        // 如果清空选择，只清空供应商信息
        this.form.customerId = null;
        this.form.customerName = '';
        return;
      }

      const findSupplier = (options, id) => {
        for (const option of options) {
          if (option.id === id) return option;
          if (option.children && option.children.length) {
            const found = findSupplier(option.children, id);
            if (found) return found;
          }
        }
        return null;
      };

      const supplier = findSupplier(this.supplierOptions, value);
      if (supplier) {
        this.form.supplierId = supplier.id;
        this.form.supplierName = supplier.id.toString();
      }
    },
    // 修改数据标准化方法
    normalizer(node) {
      return {
        id: node.id,
        label: node.supplierName,
        children: node.children
      };
    },
    /** 切换折扣类型 */
    switchDiscountType(type) {
      console.log('切换折扣类型:', type);

      // 保存当前状态，以便在切换类型后保持总金额不变
      const totalBeforeDiscount = this.totalAmount;
      const currentDiscountedAmount = parseFloat(this.form.discountedAmount) || 0;

      // 使用 Vue.$set 确保响应式更新
      this.$set(this.form, 'discountType', type);

      if (type === 'percent') {
        // 从优惠金额切换到折扣率
        if (totalBeforeDiscount > 0) {
          const discountPercent = (currentDiscountedAmount / totalBeforeDiscount) * 100;
          this.$set(this.form, 'discount', discountPercent.toFixed(2));
        } else {
          this.$set(this.form, 'discount', '100');
        }
      } else {
        // 从折扣率切换到优惠金额
        const discountAmount = totalBeforeDiscount - currentDiscountedAmount;
        this.$set(this.form, 'discount', discountAmount.toFixed(2));
      }

      // 使用 setTimeout 确保在下一个事件循环中计算总金额
      setTimeout(() => {
        this.calculateTotal();
      }, 0);
    },
    /** 处理文件上传 */
    handleFileChange(file, fileList) {
      this.form.fileList = fileList.slice(0, 5); // 最多5个文件

      // 检查文件大小
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB!');
        const index = this.form.fileList.indexOf(file);
        if (index !== -1) {
          this.form.fileList.splice(index, 1);
        }
        return false;
      }
      return true;
    },
    /** 处理本次实付变化 */
    handleActualPaymentChange(value) {
      const actualPayment = parseFloat(value) || 0;
      const totalAmount = parseFloat(this.form.totalAmount) || 0;

      // 如果本次实付超过本单应付，则设置为本单应付
      if (actualPayment > totalAmount) {
        this.$message.warning('本次实付不能超过本单应付');
        this.form.actualPayment = totalAmount.toFixed(2);
      }

      // 计算待付金额
      this.calculatePendingPayment();
    },
    // 处理商品选择确认
    handleGoodsSelectConfirm(selectedGoods) {
      console.log('选择的商品:', selectedGoods);

      if (!selectedGoods || selectedGoods.length === 0) {
        console.log('没有选择商品');
        return;
      }

      // 更新当前行
      if (this.activeRowIndex >= 0 && selectedGoods.length > 0) {
        // 使用更可靠的方式更新商品行
        const goods = selectedGoods[0];
        const updatedRow = {
          id: null,
          goodsId: goods.id,
          goodsSpec: goods.goodsSpec,
          specification: goods.specification,
          goodsCode: goods.goodsCode,
          barcode: goods.barcode,
          unit: goods.primaryUnit,
          quantity: goods.quantity || 1,
          unitPrice: goods.unitPrice || 0,
          totalPrice: goods.totalPrice || ((goods.quantity || 1) * (goods.unitPrice || 0)).toFixed(2),
          remark: ""
        };

        // 确保索引有效
        if (this.activeRowIndex < this.form.goodsList.length) {
          // 替换现有行
          this.$set(this.form.goodsList, this.activeRowIndex, updatedRow);
        } else {
          // 添加新行
          this.form.goodsList.push(updatedRow);
        }
      }

      // 如果选择了多个商品，在当前行后面添加新行
      if (selectedGoods.length > 1) {
        let insertIndex = this.activeRowIndex >= 0 ? this.activeRowIndex + 1 : 0;
        const newRows = [];

        for (let i = 1; i < selectedGoods.length; i++) {
          const goods = selectedGoods[i];
          const newRow = {
            id: null,
            goodsId: goods.id,
            goodsSpec: goods.goodsSpec,
            specification: goods.specification,
            goodsCode: goods.goodsCode,
            barcode: goods.barcode,
            unit: goods.primaryUnit,
            quantity: goods.quantity || 1,
            unitPrice: goods.unitPrice || 0,
            totalPrice: goods.totalPrice || ((goods.quantity || 1) * (goods.unitPrice || 0)).toFixed(2),
            remark: ""
          };
          newRows.push(newRow);
        }

        // 在当前行后面插入新行
        this.form.goodsList.splice(insertIndex, 0, ...newRows);
      }

      // 关闭商品选择器
      this.goodsSelectVisible = false;

      // 重置选择器状态
      this.selectedGoodsList = [];
      this.activeRowIndex = -1;

      // 强制更新视图
      this.$nextTick(() => {
        this.$forceUpdate();

        // 重新计算总金额
        this.calculateTotal();

        // 打印更新后的商品列表，用于调试
        console.log('更新后的商品列表:', JSON.parse(JSON.stringify(this.form.goodsList)));
      });
    },
    /** 查看按钮操作 */
    async handleView(row) {
      console.log(row)
      // this.viewForm = { 
      //   id: row.id,
      //   receiptCode: row.receiptCode,
      //   supplierName: row.supplierName,
      //   supplierId: row.supplierId,
      //   salesman: row.salesman,
      //   businessDate: row.businessDate,
      //   totalAmount: row.totalAmount || "0.00",
      //   discountType: row.discountType || "percent",
      //   discount: row.discount || "100",
      //   discountAmount: row.discountAmount || "0.00",
      //   discountedAmount: row.discountedAmount || "0.00",
      //   freight: row.freight || "0.00",
      //   depositDeduction: row.depositDeduction || "0.00",
      //   actualPayment: row.actualPayment || "0.00",
      //   pendingPayment: row.pendingPayment || "0.00",
      //   paymentMethod: row.paymentMethod || "现金",
      //   paymentAttachment: row.paymentAttachment,
      //   status: row.status || "0",
      //   remark: row.remark || "",
      //   goodsList: []
      // };
      const customerRes = await getCustomer(row.customerId)
      row.customerName = customerRes.data.customerName
      this.viewForm = row
      // 根据客户 id 查询客户信息
    
      // 获取商品列表
      if (this.viewForm.receiptCode) {
        const res = await getSalesByReceiptCode(this.viewForm.receiptCode)

        // 处理商品数据
        this.viewForm.goodsList = res.data.salesDetailItemList.map(item => ({
          id: item.id,
          goodsId: item.goodsId,
          goodsSpec: item.goodsSpec,
          specification: item.specification,
          goodsCode: item.goodsCode,
          barcode: item.barcode,
          unit: item.unit,
          quantity: item.quantity || 1,
          unitPrice: item.unitPrice || 0,
          totalPrice: item.totalPrice || ((item.quantity || 1) * (item.unitPrice || 0)).toFixed(2),
          remark: item.remark || ""
        }));
      }

      if (this.viewForm.supplierId) {
        const res = await getCategory(this.viewForm.supplierId)
        this.viewForm.supplierName = res.data.supplierName
      }

      this.viewOpen = true;
    },
    // 在方法中使用用户信息
    useUserInfo() {
      // 设置表单中的业务员为当前登录用户
      this.form.salesman = this.$store.state.user.name;
    },
    // 显示客户选择弹窗
    showCustomerPopover() {
      this.customerPopoverVisible = true;
      this.customerPageNum = 1; // 重置为第一页
      this.loadCustomerList();
    },

    // 切换客户选择弹窗显示状态
    toggleCustomerPopover() {
      this.customerPopoverVisible = !this.customerPopoverVisible;
      if (this.customerPopoverVisible) {
        this.loadCustomerList();
      }
    },

    // 加载客户列表
    loadCustomerList() {
      this.customerLoading = true;

      // 调用API获取客户列表
      listCustomer({
        pageNum: this.customerPageNum,
        pageSize: this.customerPageSize,
        customerName: this.customerKeyword
      }).then(response => {
        this.customerList = response.rows;
        this.customerTotal = response.total;
        this.customerLoading = false;
      }).catch(() => {
        this.customerLoading = false;
      });
    },

    // 搜索客户
    searchCustomers() {
      // 使用防抖处理输入搜索
      if (this.customerSearchTimer) {
        clearTimeout(this.customerSearchTimer);
      }

      this.customerSearchTimer = setTimeout(() => {
        this.customerPageNum = 1; // 搜索时重置为第一页
        this.loadCustomerList();
      }, 300);
    },

    // 选择客户
    handleCustomerSelect(row) {
      console.log(row);
      this.selectedCustomer = row;
      this.form.customerId = row.id;
      this.selectedCustomerName = row.customerName;
      this.customerKeyword = row.customerName;
      this.customerPopoverVisible = false;

      // 应用客户专属折扣
      if (row.exclusiveDiscount && parseFloat(row.exclusiveDiscount) > 0) {
        // 设置折扣类型为百分比
        this.form.discountType = 'percent';

        // 设置折扣值为客户的专属折扣
        this.form.discount = row.exclusiveDiscount;

        // 如果有商品，重新计算总金额
        if (this.form.goodsList && this.form.goodsList.length > 0) {
          this.calculateTotal();
        }

        this.$message.success(`已应用客户专属折扣: ${row.exclusiveDiscount}%`);
      }

      // 处理客户选择后的其他逻辑
      this.handleCustomerChange(row.id);
    },

    // 处理输入框失焦事件
    handleCustomerInputBlur() {
      // 只有当鼠标不在弹窗内部时，才关闭弹窗
      if (!this.isMouseInCustomerPopover) {
        setTimeout(() => {
          this.customerPopoverVisible = false;
        }, 200);
      }
    },
    handleCustomerSizeChange(size) {
      this.customerPageSize = size;
      this.loadCustomerList();
    },
    handleCustomerCurrentChange(page) {
      this.customerPageNum = page;
      this.loadCustomerList();
    },
  },
  watch: {
    // 修改 watch 的写法
    'form.freight': {
      handler: 'handleFreightChange',
      immediate: true  // 添加 immediate: true，确保初始化时也会触发
    },
    // 添加对discount的监听
    'form.discount': {
      handler: 'calculateTotal',
      immediate: false  // 不需要初始化触发，避免覆盖其他计算
    }
  }
};
</script>

<style scoped>
/* 进货单弹窗样式 */
.receipt-dialog /deep/ .el-dialog__body {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}

.receipt-container {
  width: 100%;
}

/* 确保底部按钮正确显示 */
.dialog-footer {
  text-align: right;
  padding-top: 10px;
}

/* 顶部信息区域 */
.receipt-header {
  display: flex;
  justify-content: space-between;
  padding: 5px 20px;
  background-color: #fff;
}

.header-left,
.header-right {
  display: flex;
  align-items: center;
}

.header-right .info-item {
  margin-left: 20px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  width: 80px;
  text-align: left;
  padding-right: 10px;
  color: #606266;
}

.supplier-input,
.salesman-select,
.date-picker {
  width: 200px;
}

/* 商品导入按钮 */
.goods-import {
  padding: 10px 20px;
  background-color: #fff;
  margin-top: 10px;
}

/* 商品表格 */
.goods-table {
  background-color: #fff;
  padding: 0 20px 10px;
}

.no-border /deep/ .el-input__inner {
  border: none;
  background-color: transparent;
  padding-left: 5px;
  padding-right: 5px;
}

.number-input /deep/ .el-input__inner {
  padding-right: 25px;
  text-align: center;
}

.table-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
}

.footer-summary {
  font-size: 14px;
  color: #606266;
}

.amount-text {
  margin-left: 20px;
  font-weight: bold;
}

/* 底部结算区域 - 完全按照UI图还原 */
.bottom-section {
  margin-top: 10px;
}

.bottom-watch-section {
  margin-top: 80px;
}

.calculation-area {
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 2px;
}

.bottom-area {
  background-color: #fff;
  padding: 15px 0px;
  margin: 0px 20px;
  border-radius: 2px;
  border-top: 1px solid #DCDFE6;
  border-bottom: 1px solid #DCDFE6;
}

.calc-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.calc-row:last-child {
  margin-bottom: 0;
}

.calc-label {
  width: 70px;
  text-align: right;
  padding-right: 10px;
  color: #606266;
  font-size: 14px;
}

.calc-input {
  width: 195px;
}

.calc-input+.calc-label {
  margin-left: 20px;
}

.payment-method {
  width: 120px;
  margin-left: 10px;
}

.total-row {
  margin-top: 20px;
  margin-bottom: 20px;
  padding-top: 15px;
  border-top: 1px dashed #dcdfe6;
}

.total-value {
  font-size: 18px;
  font-weight: bold;
  color: #00b0f0;
  margin-left: 5px;
}

.remark-section {
  background-color: #fff;
  padding: 15px 20px;
  margin-top: 10px;
  border-radius: 2px;
}

.remark-label {
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
}

.remark-textarea {
  width: 60%;
  margin-bottom: 10px;
}

.attachment-section {
  background-color: #fff;
  padding: 15px 20px;
  margin-top: 10px;
  display: flex;
  border-radius: 2px;
}

.attachment-upload {
  margin-right: 20px;
}

.upload-button {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.upload-button:hover {
  border-color: #409EFF;
}

.upload-button .el-icon-plus {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 5px;
}

.upload-text {
  color: #8c939d;
  font-size: 14px;
}

.upload-tips {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
  align-self: flex-end;
  margin-bottom: 10px;
}

/* 调整输入框样式以匹配UI */
.el-input.is-disabled .el-input__inner {
  color: #606266;
  background-color: #f5f7fa;
}

.el-select .el-input .el-select__caret {
  color: #c0c4cc;
}

/* 确保表单元素高度一致 */
.el-input--small .el-input__inner,
.el-select--small .el-input__inner,
.el-input-number--small,
.el-textarea--small .el-textarea__inner {
  height: 32px;
  line-height: 32px;
}

/* 商品选择弹窗 */
.goods-select-dialog /deep/ .el-dialog__body {
  padding: 20px;
}

.goods-search {
  margin-bottom: 15px;
}

.discount-type-switch {
  margin-bottom: 15px;
}

.switch-item {
  display: inline-flex;
  align-items: center;
  /* background-color: #e1f3ff; */
  /* color: #00b0f0; */
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.switch-item i {
  margin-left: 5px;
}

/* 下拉菜单样式 */
.el-dropdown-menu {
  padding: 5px 0;
}

.el-dropdown-menu__item {
  font-size: 14px;
  padding: 8px 16px;
}

.el-dropdown-menu__item:hover {
  background-color: #f5f7fa;
  color: #409EFF;
}

/* 优化折扣/优惠金额样式 */
.dropdown-label {
  display: inline-flex;
  align-items: center;
  color: #606266;
  cursor: pointer;
  font-size: 14px;
}

.dropdown-label:hover {
  color: #409EFF;
}

.dropdown-label i {
  margin-left: 5px;
  font-size: 12px;
}

/* 确保计算行对齐 */
.calc-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.calc-label {
  width: 100px;
  text-align: right;
  padding-right: 10px;
  color: #606266;
  font-size: 14px;
}

.calc-label-buttom {
  width: 70px;
  text-align: left;
  padding-right: 10px;
  color: #606266;
  font-size: 14px;
}

.calc-input {
  width: 195px;
}

.calc-input+.calc-label {
  margin-left: 15px;
}

/* 确保下拉菜单不影响布局 */
.el-dropdown {
  display: inline-block;
}

/* 添加输入框单位样式 */
.input-with-unit {
  position: relative;
  width: 100%;
}

.input-unit {
  position: absolute;
  right: 10px;
  top: 0;
  height: 32px;
  line-height: 32px;
  color: #606266;
  font-size: 14px;
  z-index: 1;
}

.input-with-unit .el-input__inner {
  padding-right: 25px;
}

/* 添加表格行悬停样式 */
.hoverable-row {
  cursor: pointer;
}

.hoverable-row:hover {
  background-color: #f5f7fa !important;
}

/* 高亮当前行 */
.el-table__row.current-row {
  background-color: #f0f9ff !important;
}

/* 确保输入框在悬停时不受影响 */
.hoverable-row:hover .el-input__inner,
.hoverable-row:hover .el-input-number__decrease,
.hoverable-row:hover .el-input-number__increase {
  background-color: transparent;
}

/* 确保表格内的输入框无边框 */
.no-border .el-input__inner {
  border: none;
  background-color: transparent;
}

/* 确保表格内的数字输入框无边框 */
.no-border.el-input-number {
  width: 100%;
}

.no-border .el-input-number__decrease,
.no-border .el-input-number__increase {
  border: none;
  background-color: transparent;
}

/* 商品名称单元格样式 */
.goods-name-cell {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  padding: 5px 0;
  transition: background-color 0.2s;
}

/* 悬停或聚焦状态的单元格 */
.cell-hovered {
  background-color: #fff !important;
}

.goods-name-input {
  width: 100%;
}

/* 选择按钮包装器 */
.select-btn-wrapper {
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  display: flex;
  align-items: center;
  background-color: white;
  padding: 0 5px;
  border-radius: 0 4px 4px 0;
}

.select-btn {
  color: #409EFF;
  padding: 0 5px;
  background-color: white;
}

/* 确保表格内的输入框无边框和透明背景 */
.no-border .el-input__inner {
  border: none;
  background-color: transparent;
}

/* 确保表格行悬停不影响商品名称的白色背景 */
.hoverable-row:hover .cell-hovered {
  background-color: #fff !important;
}

/* 确保表格行悬停不影响输入框 */
.hoverable-row:hover .cell-hovered .el-input__inner {
  background-color: transparent !important;
}

/* 聚焦状态的输入框 */
.goods-name-input .el-input__inner:focus {
  background-color: transparent !important;
}

/* 输入单元格样式 */
.input-cell {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  padding: 5px 0;
  transition: background-color 0.2s;
}

/* 禁用状态的输入框样式 */
.el-input.is-disabled .el-input__inner,
.el-input-number.is-disabled .el-input__inner {
  color: #c0c4cc;
  background-color: #f5f7fa;
  cursor: not-allowed;
}

/* 确保禁用状态的输入框在表格中显示正确 */
.no-border.is-disabled .el-input__inner {
  border: none;
  background-color: #f5f7fa !important;
}

/* 悬停或聚焦状态的单元格 */
.cell-hovered {
  background-color: #fff !important;
}

/* 确保表格行悬停不影响输入单元格的白色背景 */
.hoverable-row:hover .cell-hovered {
  background-color: #fff !important;
}

/* 确保表格行悬停不影响输入框 */
.hoverable-row:hover .cell-hovered .el-input__inner {
  background-color: transparent !important;
}

/* 序号列样式 */
.index-cell {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 操作按钮容器 */
.index-operations {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  gap: 4px;
  /* 添加按钮之间的间距 */
}

/* 添加和删除按钮样式 */
.index-operations i {
  width: 15px;
  height: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #409EFF;
  font-size: 12px;
  border-radius: 40px;
  /* 圆形按钮 */
  border: 1px solid #409EFF;
  /* 添加边框 */
  transition: all 0.3s;
  background-color: #fff;
}

.index-operations i:hover {
  background-color: #409EFF;
  color: #fff;
}

/* 确保序号列的内容正确显示 */
.el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 搜索结果下拉框样式 - 使用 el-table */
.search-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  width: 600px;
  max-height: 300px;
  overflow-y: auto;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 2000;
  padding: 0;
}

.search-dropdown .el-table {
  margin: 0;
}

.search-dropdown .el-table__body tr {
  cursor: pointer;
}

.search-dropdown .el-table__body tr:hover>td {
  background-color: #f5f7fa !important;
}

.search-empty {
  padding: 10px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 导入对话框样式 */
.el-upload-dragger {
  width: 100%;
  height: auto;
  padding: 30px 0;
}

.el-upload__text {
  margin: 10px 0;
  font-size: 14px;
  color: #606266;

  em {
    color: #409EFF;
    font-style: normal;
  }
}

.text-center {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}

.supplier-input {
  width: 300px;
}

/* 查看进货单样式 */
.receipt-view-container {
  width: 100%;
}

.remark-content {
  padding: 10px;
  /* background-color: #f8f8f8; */
  border-radius: 4px;
  min-height: 40px;
}

.attachment-label,
.remark-label {
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
}

.attachment-content {
  display: flex;
  flex-wrap: wrap;
}

/* 客户选择相关样式 */
.customer-select-wrapper {
  position: relative;
  width: 300px;
}

.selected-customer-info {
  font-size: 12px;
  color: #409EFF;
  margin-top: 5px;
}

/* 确保弹出的表格样式正确 */
.customer-table-popover {
  padding: 0;
}

.customer-table-popover .el-table {
  margin: 0;
}

.customer-table-popover .el-table__body tr {
  cursor: pointer;
}

.customer-table-popover .el-table__body tr:hover>td {
  background-color: #f5f7fa !important;
}

.customer-pagination {
  margin-top: 10px;
  text-align: right;
}

/* 已有样式保持不变 */

/* 客户表格容器样式 */
.customer-table-wrapper {
  width: 550px;
}

/* 分页组件样式 */
.customer-pagination {
  margin-top: 10px;
  text-align: center;
  padding: 5px 0;
}

/* 确保弹出的表格样式正确 */
.customer-table-popover {
  padding: 10px;
}

/* 其他样式保持不变 */
</style>